import time
import openai
from flask_restful import Resource, reqparse
from util import chatbot

# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('content', type=str, required=True, help='content is required.')
parser.add_argument('uid', type=str, default='')
parser.add_argument('isGpt_4', type=bool, default=False)


# 汇言
class chat(Resource):
    def post(self):
        args = parser.parse_args()
        content: str = args.get('content')
        uid: str = args.get('uid')
        isGpt_4: str = args.get('isGpt_4')

        a = "gpt-4" if isGpt_4 else "gpt-3.5-turbo-16k"
        print(a)

        if content is None:
            return {'status': 400, 'msg': 'content参数异常！'}
        if content is None:
            return {'status': 400, 'msg': 'uid参数异常！'}
        if content == "重置":
            chatbot.reset_chat_log(chatbot.chat_log, uid)
            return '已重置输入！！！'

        for count in range(0, 64):
            try:
                res = chatbot.ask(uid, content, chatbot.chat_log, isGpt_4)
                return res
            except openai.error.RateLimitError as e:
                print("一分钟之内只能请求三次，请稍后再试", "等待3秒")
                continue
                # return "一分钟之内只能请求三次，请稍后再试"
            except openai.error.InvalidRequestError as e:
                print("上下文字数超出限制，请重置", "等待3秒")
                chatbot.reset_chat_log(chatbot.chat_log, uid)
                continue
                # return "上下文字数超出限制，请重置"
            except Exception as e:
                print("其他异常", "等待3秒")
                continue
                # return ""